package com.wisedu.mobile.common;

import com.wisedu.mobile.common.domain.LoginUser;
import com.wisedu.mobile.common.service.TokenService;
import com.wisedu.mobile.common.utils.ServletUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.FieldMatcher;
import org.nutz.http.*;
import org.nutz.json.Json;
import org.nutz.lang.Each;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.trans.Atom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 通用Controller
 *
 * @param <T> 实体类
 */
public class BaseController<T> {

    @Autowired
    private BaseServiceImpl<T> baseService;

    @Autowired
    private TokenService tokenService;

    @Value("${moblie.apiCtx}")
    private String apiCtx;

    @Value("${token.header}")
    private String header;

    @GetMapping("index")
    public ModelAndView index(HttpServletRequest request){
        return new ModelAndView(request.getRequestURI().substring(7));
    }

    @PostMapping("page")
    public AjaxResult<TableDataInfo<T>> page(int pageNumber, int pageSize,T entityVo,String desc,String asc) {
        Cnd cnd = null;
        if(entityVo!=null){
            cnd = Cnd.from(baseService.dao(),entityVo,FieldMatcher.create(false));
        }
        if(!Strings.isEmpty(desc)){
            cnd.desc(desc);
        }
        if(!Strings.isEmpty(asc)){
            cnd.asc(asc);
        }
        return AjaxResult.success(baseService.listPage(pageNumber, pageSize,cnd));
    }

    @PostMapping("list")
    public AjaxResult<List<T>> list() {
        return null;
    }

    @GetMapping("get/{id}")
    public AjaxResult<T> get(@PathVariable("id") String id) {
        return AjaxResult.success(baseService.fetch(id));
    }

    @PostMapping("save")
    public AjaxResult<T> save(T entityVo) {
        if(entityVo==null){
            return AjaxResult.error();
        }
        Mirror mirror = Mirror.me(entityVo.getClass());
        Object id = mirror.getValue(entityVo, "id");
        String currentId = getCookie(ServletUtils.getRequest(),"uid");
        if(id==null||"".equals(id)){
            mirror.setValue(entityVo, "createBy", currentId);
            baseService.insert(entityVo);
        }else{
            mirror.setValue(entityVo, "updateTime", new Date());
            mirror.setValue(entityVo, "updateBy", currentId);
            FieldFilter.locked(entityVo.getClass(), "^createBy|createTime$").run(new Atom(){
                @Override
                public void run(){
                    baseService.update(entityVo);
                }
            });

        }
        return AjaxResult.success();
    }

    @DeleteMapping("delete/{id}")
    public AjaxResult<T> delete( @PathVariable("id") String id) {
        return AjaxResult.success(baseService.delete(id));
    }

    @DeleteMapping("deleteBatch")
    public AjaxResult<T> deleteBatch(@RequestBody List<String> ids){
        return null;
    }
    /*
    批量删除,前端调用：
            $.ajax({
        url: ctx + "deleteBatch",
                type: "DELETE",
                data: JSON.stringify([id1,id2]),
        dataType: "JSON",
                contentType: 'application/json',
                success: function (data) {

        }
    });
    */
    private String getCookie(HttpServletRequest request,String cookieName){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }
    public  AjaxResult post(HttpServletRequest request, String url, Map<String, String>  params){
        try {
            String token = getCookie(request,"token");
            if(token==null){
                return AjaxResult.error("auth denied");
            }
            Header head = Header.create().set(header,token);
            String body = "";
            if(params!=null) {
                StringBuffer sb = new StringBuffer();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }
                body = sb.substring(0,sb.length()-1);
            }
            Response response = Http.post3(apiCtx+url,
                    body,head,
                    5 * 1000);
            return Json.fromJson(AjaxResult.class,response.getContent());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
